package com.wkhyapp.lm.view;

import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.loadmore.LoadMoreView;
import com.google.gson.reflect.TypeToken;
import com.lidong.photopicker.intent.PhotoPreviewIntent;
import com.lidong.photopicker.intent.PhotoPreviewIntent2;
import com.wkhyapp.lm.R;
import com.wkhyapp.lm.adapter.GoodsAdapter;
import com.wkhyapp.lm.adapter.SearchShopAdapter;
import com.wkhyapp.lm.base.SuperActivity;
import com.wkhyapp.lm.contract.SearchResultPresenter;
import com.wkhyapp.lm.contract.SearchResultView;
import com.wkhyapp.lm.fragment.DTFragment;
import com.wkhyapp.lm.http.vo.Goods;
import com.wkhyapp.lm.http.vo.Member;
import com.wkhyapp.lm.utils.PreferenceUtils;
import com.wkhyapp.lm.utils.StatusBarFontUtil;
import com.wkhyapp.lm.utils.StringUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;

public class SearchResultActivity extends SuperActivity<SearchResultPresenter> implements SearchResultView{


    @BindView(R.id.refresh_view)
    SwipeRefreshLayout refresh_view;
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;
    @BindView(R.id.key_tv)
    TextView key_tv;
    private GoodsAdapter goodsAdapert;
    private List<Goods> goods;
    private int mCurrentPage = 1;
    String key;
    @BindView(R.id.back_iv)
    ImageView back;
    @BindView(R.id.search_rl)
    RelativeLayout search_rl;
    private View headView;
    private GridView gridView;
    SearchShopAdapter searchShopAdapter;
    private RelativeLayout head_rl;
    private int categoryId = 0;
    @Override
    public void initUI() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            translucentStatusBar();
        }
        StatusBarFontUtil.setLightStatusBarColor(this);
        key = getIntent().getStringExtra("0");
        categoryId = getIntent().getIntExtra("1",0);
        goods = new ArrayList<>();

        headView = View.inflate(mContext, R.layout.search_head, null);
        gridView = (GridView) headView.findViewById(R.id.grid_vi);
        head_rl = (RelativeLayout) headView.findViewById(R.id.head_rl);

        goodsAdapert = new GoodsAdapter(R.layout.item_goods_ss_grid,goods);
        refresh_view.setColorSchemeColors(Color.parseColor("#FFEC48"),Color.parseColor("#FFEC48"));
        GridLayoutManager manager = new GridLayoutManager(getContext(),2);
        manager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (position == recycler_view.getAdapter().getItemCount() - 1) {
                    return 2;
                }
                return 1;
            }
        });

        recycler_view.setLayoutManager(manager);
        int space = getResources().getDimensionPixelSize(R.dimen.item_space);
        recycler_view.addItemDecoration(new SearchResultActivity.SpaceItemDecoration(space));
        recycler_view.setAdapter(goodsAdapert);
        refresh_view.setRefreshing(false);

        if(!StringUtils.isEmpty(key)){
            showLoad("数据加载中...");
            if(key.startsWith("http")){
                goods.clear();
                mPresenter.getDate(key,mCurrentPage);
            }else{
                key_tv.setText(key+"");
                List<String> list= gson.fromJson(PreferenceUtils.getInstance().getPrefString("keys",""), new TypeToken<List<String>>() {}.getType());
                if(list==null){
                    list = new ArrayList<>();
                }else{
                    if(!list.contains(key)){
                        list.add(key);
                    }
                }
                if(categoryId<=0){
                    PreferenceUtils.getInstance().setPrefString("keys",gson.toJson(list));
                }
                mPresenter.getSearchDate(key,mCurrentPage);
                mPresenter.getShop(key);
            }
        }
    }

    @Override
    protected void afterCreate() {

    }

    @Override
    protected void initListener() {
        goodsAdapert.setLoadMoreView(new LoadMoreView() {
            @Override
            public int getLayoutId() {
                return R.layout.view_index_load_more;
            }

            @Override
            protected int getLoadingViewId() {
                return com.chad.library.R.id.load_more_loading_view;
            }
            @Override
            protected int getLoadFailViewId() {
                return com.chad.library.R.id.load_more_load_fail_view;
            }
            @Override
            protected int getLoadEndViewId() {
                return com.chad.library.R.id.load_more_load_end_view;
            }
        });

        goodsAdapert.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                mCurrentPage = mCurrentPage+1;
                if(key.startsWith("http")){
                    mPresenter.getDateMore(mCurrentPage,key);
                }else{
                    mPresenter.getSearchDateMore(key,mCurrentPage);
                }


            }
        });
        refresh_view.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mCurrentPage = 1;
                if(key.startsWith("http")){
                    mPresenter.getDate(key,mCurrentPage);
                }else{
                    mPresenter.getSearchDate(key,mCurrentPage);
                }

            }
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        goodsAdapert.setCallBack(new GoodsAdapter.callBack() {
            @Override
            public void share(Goods item) {
                goTo(ShareGoodsActivity.class,item.getId());
            }

            @Override
            public void showImg(Goods item) {
                PhotoPreviewIntent2 intent = new PhotoPreviewIntent2(SearchResultActivity.this);
                intent.setCurrentItem(0);
                intent.setPhotoPaths(item.getGoodsImgs());
                startActivityForResult(intent, 1);
            }

            @Override
            public void info(Goods item) {
                goTo(GoodsInfoActivity.class,item.getId());
            }

            @Override
            public void shop(Goods item) {
                goTo(ShopActivity.class,item.getUserId());
            }

        });
        search_rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    public void setMember(List<Member> members) {
        if(members!=null){

            if(members.size()>0){
                head_rl.setVisibility(View.VISIBLE);
                searchShopAdapter = new SearchShopAdapter(mContext,members,R.layout.item_search_shop);
                gridView.setAdapter(searchShopAdapter);
                goodsAdapert.addHeaderView(headView);
                goodsAdapert.notifyDataSetChanged();
                searchShopAdapter.setCallBack(new SearchShopAdapter.callBack() {
                    @Override
                    public void action(Member item) {
                        goTo(ShopActivity.class,item.getId());
                    }
                });
            }else {
                head_rl.setVisibility(View.GONE);
            }

        }

    }

    @Override
    public void setGoods(List<Goods> goodsList) {

        dismissLoad();
        goods.clear();
        if(goodsList!=null&&goodsList.size()>0){
            goods.addAll(goodsList);
        }
        goodsAdapert.removeAllHeaderView();
        goodsAdapert.addHeaderView(headView);

        goodsAdapert.notifyDataSetChanged();
        refresh_view.setRefreshing(false);
        goodsAdapert.loadMoreComplete();


    }


    @Override
    public void setGoodsMore(List<Goods> goodsMore) {
        if(goodsMore.size()==0){
            goodsAdapert.loadMoreComplete();
            goodsAdapert.loadMoreEnd();
        }else{
            goods.addAll(goodsMore);
            goodsAdapert.notifyDataSetChanged();
            goodsAdapert.loadMoreComplete();
        }
    }

    @Override
    protected SearchResultPresenter createPresenter() {
        return mPresenter = new SearchResultPresenter(this);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_search_result;
    }

    public class SpaceItemDecoration extends RecyclerView.ItemDecoration {
        private int space;
        public SpaceItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            //不是第一个的格子都设一个左边和底部的间距
            outRect.left = space;
            outRect.bottom = space;
            //由于每行都只有3个，所以第一个都是3的倍数，把左边距设为0
            if (parent.getChildLayoutPosition(view) %3==0) {
                outRect.left = 0;
            }
        }
    }

}
